﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MstscHelperApp
{
    internal static class MstscStartHelpr
    {
        public static string StartMstsc(MsctcInfo msctcInfo)
        { 
            try
            {
                if (msctcInfo == null)
                {
                    MessageBox.Show("远程连接信息不能为空");
                    return "";
                }
                string server = msctcInfo.IP;
                string username = msctcInfo.UserName;
                string password = msctcInfo.Password;

                // 存储凭据到 Windows 凭据管理器
                StoreCredentials(server, username, password);

                var displayName = server;
                // 如果包含端口，提取主机名和端口用于显示
                if (server.Contains(":"))
                {
                    var parts = server.Split(':');
                    if (parts.Length > 0)
                    {
                        displayName = parts[0]; // 显示名称不包含端口，更简洁
                    }
                }
                var displayUserName = username;
                if (username.Contains("\\"))
                {
                    var parts = username.Split('\\');
                    if (parts.Length > 0)
                    {
                        displayUserName = parts[1];
                    }
                }
                // 生成 RDP 文件路径
                string rdpFilePath = Path.Combine(Path.GetTempPath(), $"{displayName}_{displayUserName}.rdp");
                 
                // 创建简化的 RDP 文件内容
                string rdpContent = $"full address:s:{server}\n" +
                                   $"username:s:{username}\n" +
                                   $"window title:s:远程连接 - {displayName}\n" +
                                   "screen mode id:i:2\n" +         // 全屏模式
                                   "disable wallpaper:i:1\n" +     // 禁用壁纸以提高性能
                                   "authentication level:i:2\n";  // 要求服务器身份验证

                // 写入 RDP 文件
                File.WriteAllText(rdpFilePath, rdpContent);

                // 启动远程桌面连接
                using (Process process = new Process())
                {
                    process.StartInfo = new ProcessStartInfo
                    {
                        FileName = "mstsc.exe",
                        Arguments = $"\"{rdpFilePath}\"",
                        UseShellExecute = false,
                        CreateNoWindow = true
                    };

                    process.Start(); 
                   // Cleanup(rdpFilePath, server);
                }
                return rdpFilePath; // 返回 RDP 文件路径
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动远程桌面连接时出错: {ex.Message}");
                return "";
            }
        }
        private static void StoreCredentials(string server, string username, string password)
        {
            string target = $"TERMSRV/{server}";

            string user =username;

            // 使用 cmdkey 命令存储凭据
            using (Process process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                {
                    FileName = "cmdkey.exe",
                    Arguments = $" /add:\"{target}\" /user:\"{user}\" /pass:\"{password}\"",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                };

                process.Start();
                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    string error = process.StandardError.ReadToEnd();
                    MessageBox.Show($"存储凭据失败: {error}");
                    return;
                }
            }
        }

        public static bool IsConnectedToRemoteDesktop(string targetIp)
        {
            try
            {
                // 创建 WMI 查询，获取远程桌面会话信息
                string query = "SELECT * FROM Win32_Process WHERE Name = 'mstsc.exe'";
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
                {
                    var a = searcher.Get();
                    foreach (ManagementObject session in searcher.Get())
                    {
                        // 获取进程命令行参数
                        string commandLine = session["CommandLine"]?.ToString() ?? "";

                        // 检查命令行参数中是否包含目标IP
                        if (commandLine.Contains(targetIp))
                        {
                            return true;
                        }
                    }
                }

                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"检查远程桌面连接时发生错误: {ex.Message}");
                return false;
            }
        }

       
    }
}
